<template>
  <view class="edit-info-view">
    <!-- 提示信息弹窗 -->
    <uni-popup ref="message" type="message">
      <uni-popup-message :type="data.msgType" :message="data.messageText" :duration="2000"></uni-popup-message>
    </uni-popup>
    <!-- 头像编辑 -->
    <view class="edit-avatar-box">
      <image @click="changeAvatar" class="avatar" :src="data.avatar"></image>
    </view>
    <!-- 资料编辑 -->
    <view>
      <view class="edit-item">
        <text class="edit-tag">名字</text>
        <input v-model="data.userName" class="e-input" type="text" placeholder="名字(20)" maxlength="20"/>
      </view>
      <view class="edit-item">
        <text class="edit-tag">账号</text>
        <input v-model="data.account" class="e-input" type="number" placeholder="账号(15)" maxlength="15"/>
      </view>
      <view class="edit-des-item">
        <text class="edit-tag">简介</text>
        <textarea class="des-textarea" @blur="bindTextAreaBlur" placeholder="简介内容(100)" auto-height maxlength="100" v-model="data.infoDes"/>
      </view>
      <view class="edit-item">
        <text class="edit-tag">性别</text>
        <picker @change="bindPickerChange" :value="data.sex" :range="data.sexList">
          <view>{{data.sexList[data.sex]}}</view>
          <view v-if="data.sex == null" style="color: #949494;">请选择性别</view>
        </picker>
      </view>
      <view class="edit-item">
        <text class="edit-tag">生日</text>
        <picker mode="date" :value="data.birthday" :start="startDate" :end="endDate" @change="bindDateChange">
          <view>{{data.birthday}}</view>
          <view v-if="data.birthday==null || data.birthday ==''" style="color: #949494;">请选择日期</view>
        </picker>
      </view>
      <view class="edit-img-item" @click="changeImg">
        <text class="edit-tag">背景图</text>
        <image class="edit-img" mode="aspectFill" :src="data.infoBg"></image>
      </view>
    </view>
    
    <!-- 保存按钮 -->
    <button class="s-button" @click="saveInfo">保存信息</button>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs,computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import helper from '../../common/helper';

const currentDate = getMyDate({
    format: true,
})
 
const data = reactive({
  curUser: uni.getStorageSync("curUser") || null,
  avatar: "",
  userName: "",
  account: "",
  infoDes: "",
  sex: null,
  birthday: "",
  infoBg: "",
  sexList:["男","女"],
  msgType:"",
  messageText:"",
});

const message = ref(null)

function messageToggle(type,text) {
  data.msgType = type
  data.messageText = text
  message.value.open()
}

// 第一次进入页面执行
onLoad(() => {
  console.log('onLoad')
  data.curUser= uni.getStorageSync("curUser") || null
  data.account = data.curUser.account
  data.avatar = data.curUser.avatar
  data.userName = data.curUser.userName
  data.infoDes = data.curUser.infoDes
  data.sex = data.curUser.sex
  //转换日期
  data.birthday = helper.getDate(data.curUser.birthday)
  data.infoBg = data.curUser.infoBg
})

let startDate = computed(()=>{
  return getMyDate('start');
});

let endDate = computed(()=>{
  return getMyDate('end');
})

function bindPickerChange(e) {
  console.log('picker发送选择改变，携带值为', e.detail.value)
  data.sex = e.detail.value
}

function bindDateChange(e) {
  data.birthday = e.detail.value
}

function bindTextAreaBlur(e) {
  console.log(e.detail.value)
}

function getMyDate(type) {
  const date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate()

  if (type === 'start') {
      year = year - 60;
  } else if (type === 'end') {
      year = year;
  }
  month = month > 9 ? month : '0' + month;
  day = day > 9 ? day : '0' + day;
  return `${year}-${month}-${day}`;
}

function changeImg(){
  console.log("选择背景图片")
  uni.chooseMedia({
  	count: 1, //默认9
  	mediaType: ['image','video'],
    sourceType: ['album', 'camera'],
    maxDuration: 30,
    camera: 'back',
  	success: function (res) {
  		console.log(JSON.stringify(res));
      data.infoBg=res.tempFiles[0].tempFilePath
  	}
  });
}

function changeAvatar(){
  console.log("选择头像图片")
  uni.chooseMedia({
    count:1,
  	mediaType: ['image'],
    sourceType: ['album', 'camera'],
    maxDuration: 30,
    camera: 'back',
  	success: function (res) {
  		console.log(JSON.stringify(res));
      data.avatar=res.tempFiles[0].tempFilePath
  	}
  });
}

async function saveInfo(){
  console.log("保存信息"+data.avatar+" "+data.userName+" "+data.account+" "+data.infoDes+" "+data.sex+" "+data.birthday+" "+data.infoBg)
  if(data.avatar!="" || data.userName !="" || data.account !="" || data.infoDes !="" || data.sex !="" || data.birthday !="" || data.infoBg != ""){
    console.log("发送请求")
    //修改了头像
    if(data.avatar != data.curUser.avatar && data.avatar != ""){
      console.log("上传背景图"+data.avatar)
      await uploadAvatar()
    }
    if(data.infoBg != data.curUser.infoBg && data.infoBg != ""){
      console.log("上传背景图"+data.infoBg)
      await uploadInfoBg()
    }
    await saveBaseInfo()
  }  
}

function uploadAvatar(){
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: helper.webUrl + '/user/uploadAvatar',
      filePath: data.avatar,
      name: 'file',
      formData:{
        'userId':data.curUser.id
      },
      success:(res) =>{
        console.log(res.data)
        resolve(res)
      },
      fail: (err) => {
        console.error('上传失败:', err);
      },
      complete: (completeRes) => {
        console.log('上传完成, 状态:', completeRes.statusCode);
      }
    })
  });   
}

function uploadInfoBg(){
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: helper.webUrl + '/user/uploadInfoBg',
      filePath: data.infoBg,
      name: 'file',
      formData:{
        'userId':data.curUser.id
      },
      success:(res) =>{
        console.log(res.data)
        resolve(res)
      },
      fail: (err) => {
        console.error('上传失败:', err);
      },
      complete: (completeRes) => {
        console.log('上传完成, 状态:', completeRes.statusCode);
      }
    })
  });   
}

function saveBaseInfo(){
  return new Promise((resolve, reject) => {
    uni.request({
      url:helper.webUrl+'/user/saveInfo',
      method:'POST',
      header: {
          'Content-Type': 'application/json' //自定义请求头信息
      },
      data: {
        userId: data.curUser.id,
        userName: data.userName,
        account: data.account,
        infoDes: data.infoDes,
        sex: data.sex,
        birthday: data.birthday
      },
      success: (res) => {
        console.log(res.data);
        if(res.data.code == 200){
          resolve(res)
          messageToggle("success",res.data.msg)
          //保存到
          uni.removeStorageSync("curUser")
          uni.setStorageSync("curUser",res.data.data)
          let curUser = uni.getStorageSync("curUser")
          console.log(curUser)
          uni.navigateBack()
        }else{
          messageToggle("info",res.data.msg)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    })
  });   
  
}

</script>

<style scoped>
.edit-info-view{
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
}
.edit-avatar-box{
  width: 100vw;
  height: 25vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #949494;
}
.edit-item{
  width: 100vw;
  height: 7vh;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 20px;
  border-bottom: 1px solid #c5c5c5;
}
.edit-des-item,.edit-img-item{
  width: 100vw;
  min-height: 10vh;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 20px;
  border-bottom: 1px solid #c5c5c5;
  padding-right: 10px;
}
.des-textarea{
  width: 100%;
  min-height: 10vh;
  max-height: 15vh;
  font-size: 15px;
  padding: 10px;
}
.edit-tag{
  width: 50px;
}
.e-input{
  font-size: 15px;
  width: 80vw;
}
.edit-img{
  margin-left: auto;
  width: 80px;
  height: 50px;
  border-radius: 10px;
}
.s-button{
  width: 60%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 16px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}
</style>
